package org.example.cassell_admin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.example.cassell_admin.entity.AdminUser;
import org.example.cassell_admin.service.AdminService;
import org.example.cassell_client.service.BulletinServiceClient;
import org.example.cassell_client.service.DeptServiceClient;
import org.example.cassell_client.service.TipServiceClient;
import org.example.cassell_client.service.UserServiceClient;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletResponse;
import org.example.entity.Base.Result;
import org.example.util.JWTUtil;
import org.example.util.MD5Util;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Validated
@RestController
@RequestMapping("/admin")
@EnableFeignClients(basePackages = "org.example.cassell_client.service")
public class AdminController {
    private final AdminService adminService;
    private final BulletinServiceClient bulettinbServiceClient;
    private final UserServiceClient userServiceClient;
    private final DeptServiceClient deptServiceClient;
    private final TipServiceClient tipServiceClient;
    private final RabbitTemplate rabbitTemplate;
    public AdminController(AdminService adminService, BulletinServiceClient bulettinbServiceClient, UserServiceClient userServiceClient, DeptServiceClient deptServiceClient, TipServiceClient tipServiceClient, RabbitTemplate rabbitTemplate) {
        this.adminService = adminService;
        this.bulettinbServiceClient = bulettinbServiceClient;
        this.userServiceClient = userServiceClient;
        this.deptServiceClient = deptServiceClient;
        this.tipServiceClient = tipServiceClient;
        this.rabbitTemplate = rabbitTemplate;
    }
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> body, HttpServletResponse response){//@Pattern(regexp="^\\s{5,16}$")
        //根据用户邮箱查询用户
        String UserEmail=body.get("UserEmail");
        String UserPassWord=body.get("UserPassWord");
        AdminUser loginAdminUser = adminService.findUserByEmail(UserEmail);
        System.out.println(loginAdminUser);
        if (loginAdminUser ==null){
            return Result.error("邮箱未注册或邮箱填写错误,或权限不足");
        }
        if (MD5Util.string2MD5(UserPassWord).equals(loginAdminUser.getUserPassWord())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("Email", loginAdminUser.getUserEmail());
            claims.put("Name", loginAdminUser.getUserName());

            String token = JWTUtil.genToken(claims);
            return Result.success(token);
        } else {
            return Result.error("密码错误");
        }
    }

    @GetMapping("/bulletinlist")
    Result<PageInfo> bulletinlist(@RequestParam(name = "PageNumber", defaultValue = "1") int PageNumber, @RequestParam(name = "PageSize", defaultValue = "5") int PageSize) {
        return bulettinbServiceClient.list(PageNumber, PageSize);
    }

    @GetMapping("/bulletingetContent")
    public Object bulletingetContent(Integer id) {
        return bulettinbServiceClient.getContent(id);
    }

    @GetMapping("/deptlist")
    Result<PageInfo> deptlist(@RequestParam(name = "PageNumber", defaultValue = "1") int PageNumber, @RequestParam(name = "PageSize", defaultValue = "5") int PageSize) {
        return deptServiceClient.listbypage(PageNumber, PageSize);
    }

    @PostMapping("/tipalltip")
    Result<PageInfo> tipalltip(@RequestParam(name = "PageNumber", defaultValue = "1") int PageNumber, @RequestParam(name = "PageSize", defaultValue = "5") int PageSize) {
        return tipServiceClient.alltip(PageNumber, PageSize);
    }

    @GetMapping("/userlist")
    Result<PageInfo> userlist(@RequestParam(name = "PageNumber", defaultValue = "1") int PageNumber, @RequestParam(name = "PageSize", defaultValue = "5") int PageSize) {
        return userServiceClient.list(PageNumber, PageSize);
    }

    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody Map<String, String> params) {
        log.info("收到用户更新请求，参数：{}", params);
        try {
            // 手动序列化为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonParams = objectMapper.writeValueAsString(params);
            log.debug("发送的JSON内容：{}", jsonParams);

            rabbitTemplate.convertAndSend(
                    "user.direct",
                    "user.success",
                    jsonParams,  // 直接发送JSON字符串
                    message -> {
                        message.getMessageProperties().setContentType("application/json");
                        return message;
                    }
            );
            return Result.success("成功");
        } catch (Exception e) {
            log.error("消息发送失败", e);
            return Result.error("失败");
        }
    }
}
